package com.hw.one.collect.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.*;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/05/16 16:49.
 */
public class HttpClientUtil {

    private static Logger log = Logger.getLogger(HttpClientUtil.class);


    /**
     * http get 请求
     *
     * @param getUrl
     * @param getHeaders
     * @return
     * @throws IOException
     * @author 李亚坤
     * @createtime 2017年4月13日16:27:34
     */
    public static Map<String, String> sendGet(String getUrl, Map<String, String> getHeaders) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("get请求:" + getUrl);
        try {
            // 根据地址获取请求
            HttpGet httpGet = new HttpGet(getUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for (String pKey : getHeaders.keySet()) {
                httpGet.setHeader(pKey, getHeaders.get(pKey));
            }
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpGet);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }


    /**
     * http get 请求
     *
     * @param getUrl
     * @param getHeaders
     * @return
     * @throws IOException
     * @author 李亚坤
     * @createtime 2017年4月13日16:27:34
     */
    public static Map<String, String> sendGetWithParams(String getUrl, Map<String, String> getHeaders, Map<String, String> paramMap) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("get请求:" + getUrl);
        try {
            // 根据地址获取请求
            HttpGet httpGet = new HttpGet();

            // 设置请求头
            for (String pKey : getHeaders.keySet()) {
                httpGet.setHeader(pKey, getHeaders.get(pKey));
            }
            URIBuilder builder = new URIBuilder(getUrl);
            if (paramMap != null && !paramMap.isEmpty()) {
                builder.setParameters(paramsConverter(paramMap));
            }
            httpGet.setURI(builder.build());
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpGet);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    private static List<NameValuePair> paramsConverter(Map<String, String> params) {
        List<NameValuePair> nvps = new LinkedList<NameValuePair>();
        Set<Map.Entry<String, String>> paramsSet = params.entrySet();
        for (Map.Entry<String, String> paramEntry : paramsSet) {
            nvps.add(new BasicNameValuePair(paramEntry.getKey(),
                paramEntry.getValue()));
        }

        return nvps;
    }


    /**
     * http post 请求
     *
     * @param postUrl
     * @param postHeaders
     * @param postEntity
     * @return
     * @throws IOException
     * @author 李亚坤
     * @createtime 2017年4月13日16:28:21
     */
    public static Map<String, String> sendPost(String postUrl, Map<String, String> postHeaders, Map<String, String> postEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("post请求:" + postUrl);
        try {
            // 根据地址获取请求
            HttpPost httpPost = new HttpPost(postUrl);

            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for (String pKey : postHeaders.keySet()) {
                httpPost.setHeader(pKey, postHeaders.get(pKey));
            }
            // 拼接参数
            List<NameValuePair> nvps = new ArrayList<>();
            for (String pKey : postEntity.keySet()) {
                nvps.add(new BasicNameValuePair(pKey, postEntity.get(pKey)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    public static Map<String, String> sendPostWithStr(String postUrl, Map<String, String> postHeaders, String postEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("post请求:" + postUrl);
        try {
            // 根据地址获取请求
            HttpPost httpPost = new HttpPost(postUrl);
            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for (String pKey : postHeaders.keySet()) {
                httpPost.setHeader(pKey, postHeaders.get(pKey));
            }
            // 拼接参数
            httpPost.setEntity(new StringEntity(postEntity, ContentType.APPLICATION_JSON));
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPost);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            log.error("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    /**
     * http post 请求
     *
     * @param putUrl
     * @param putHeaders
     * @param putEntity
     * @return
     * @throws IOException
     * @author 毛超然
     * @createtime 2017年12月11日
     */
    public static Map<String, String> sendPut(String putUrl, Map<String, String> putHeaders, Map<String, String> putEntity) {
        String result;
        int statusCode;
        Map<String, String> resultMap = new HashMap<>();
        log.info("put请求:" + putUrl);
        try {
            // 根据地址获取请求
            HttpPut httpPut = new HttpPut(putUrl);

            // 获取当前客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            // 设置请求头
            for (String pKey : putHeaders.keySet()) {
                httpPut.setHeader(pKey, putHeaders.get(pKey));
            }
            // 拼接参数
            List<NameValuePair> nvps = new ArrayList<>();
            for (String pKey : putEntity.keySet()) {
                nvps.add(new BasicNameValuePair(pKey, putEntity.get(pKey)));
            }
            httpPut.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(httpPut);
            // 获取响应状态码
            statusCode = response.getStatusLine().getStatusCode();
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            resultMap.put("statusCode", String.valueOf(statusCode));
            resultMap.put("result", result);
        } catch (Exception e) {
            log.error("发送 PUT 请求出现异常！" + e);
            e.printStackTrace();
            resultMap.put("statusCode", "-1");
            resultMap.put("result", "");
            return resultMap;
        }
        return resultMap;
    }

    public static String dealResponse(Map<String, String> response) {
        if (null != response && "200".equals(response.get("statusCode"))) {
            log.info("--------------------------------------");
            log.info(response.get("result"));
            log.info("---------------------------------------");
            return response.get("result");
        } else {
            log.info("-------------------请求失败------------");
            return null;
        }
    }

    public static void main(String[] args) {
        OneAuthUtil oneAuth = OneAuthUtil.getInstance();
        String url = oneAuth.httpPre + "/api/noAuthen/savePatrolDeviceTrackData?format=json";
        Map<String, String> header = oneAuth.getAuthHeader();
        Map<String, String> body = new HashMap<>();
        body.put("deviceCode", "中文");
        String param = "deviceCode=中文";
        Map<String, String> resultMap = sendPost(url, header, body);
        StringEntity entity = new StringEntity(body.toString(), "utf-8");
//        try {
//            HttpUtil.doPost(url, header, entity);
//        } catch (HttpResponseException e) {
//            e.printStackTrace();
//        }
//        System.out.println("resultMap = " + resultMap.toString());
    }


//    public static void main(String[] args) {
//        try {
//
//
//            String url = "http://123.15.58.210/blueSky/sys/build/getBuildSiteByAreas?geos=3";
//
//            Map<String, String> resultMap = sendGetWithParams(url, new HashMap<String, String>(), new HashMap<String, String>());
//            if ("200".equals(resultMap.get("statusCode"))) {
//                String resultJson = resultMap.get("result");
//                JSONObject json = JSONObject.parseObject(resultJson);
//                JSONArray dataList = JSONArray.parseArray(json.getString("data"));
//                for (Object data : dataList) {
//                    JSONObject dataObj = JSONObject.parseObject(data.toString());
//                    String address = dataObj.getString("bsiteLoc"); // 地址
//                    String linkMan = dataObj.getString("bsiteMgr"); // 联系人
//                    String siteName = dataObj.getString("bsiteName"); // 站点名称
//                    String siteNo = dataObj.getString("bsiteNo"); // 站点代码
//                    String siteProject = dataObj.getString("bsiteProject"); // 项目名称
//                    String siteStruc = dataObj.getString("bsiteStruc"); //
//                    String siteType = dataObj.getString("bsiteType"); //
//                    String buildUnit = dataObj.getString("buildUnit"); // 建筑公司
//                    String buildId = dataObj.getString("hkBuildId"); // 建筑id
//                    String id = dataObj.getString("id"); // id
//                    String latitude = dataObj.getString("latitude"); // 纬度
//                    String linkPhone = dataObj.getString("linkphone"); // 联系电话
//                    String longitude = dataObj.getString("longitude"); // 经度
//                    String regionId = dataObj.getString("xzqhId"); // 行政区划id
//                    String regionName = dataObj.getString("xzqhMc"); // 行政区划名称
//                    String status = dataObj.getString("status"); // 状态
//
//                }
//                System.out.println("resultJson = " + resultJson);
//            }
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
